<template>
    <a-modal
      :maskClosable="false"
      :title="title"
      :width="1300"
      :bodyStyle="{
        padding: '0 24px',
      }"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭"
    >
      <a-card
        :bordered="false"
        :bodyStyle="{
          padding: '10px 24px',
        }"
      >
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <a-form-item label="单据编号">
                  <j-input placeholder="请输入单据编号" v-model="queryParam.billNo"></j-input>
                </a-form-item>
              </a-col>
              <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <a-form-item label="申请部门">
                  <j-select-depart placeholder="请选择申请部门" v-model="queryParam.departId" />
                </a-form-item>
              </a-col> -->
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <a-form-item
                  label="费用所属团队"
                  :wrapperCol="{
                    xs: { span: 24 },
                    sm: { span: 12 },
                  }"
                >
                  <!-- <select-team-input placeholder="请选择团队" v-model="queryParam.feeTeamld" :teamType="0" :tdlx="3" /> -->
                  <select-team-input placeholder="请选择团队" v-model="queryParam.feeTeamId" :teamType="0" :tdlx="3" />
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <a-button @click="searchByquery" type="primary" icon="search">查询</a-button>
                <a-button @click="searchReset(1)" style="margin-left: 8px" icon="redo">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <a-table
          ref="table"
          rowKey="id"
          bordered
          :scroll="{x:scrollX}"
          :columns="dragResizeColumns"
          :components="draggableComponent"
          :dataSource="dataSource"
          :loading="loading"
          :pagination="ipagination"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onSelectAll: onSelectAll,
            onSelect: onSelectOne,
            onChange: onSelectChange,
            type: getType,
          }"
          @change="handleTableChange"
          class="j-table-force-nowrap"
          wrapClassName="ant-modal-cust-warp"
        >
          <span slot="purchaseBill" slot-scope="text,record">
            <a href="javascript:void(0);" @click="goProjectDetail(record)">{{ text }}</a>
          </span>
        </a-table>
      </a-card>
      <erp-project-report-modal ref="projectForm"></erp-project-report-modal>
      <!-- <ErpRevokedDocFormApplyDetail ref="detailForm"></ErpRevokedDocFormApplyDetail> -->
      <ErpReportReviewModel ref="detailForm"></ErpReportReviewModel>
    </a-modal>
  </template>
  
  <script>
  import { filterObj } from '@/utils/util'
  import { queryDepartTreeList, searchByKeywords } from '@/api/api'
  import { getAction } from '@/api/manage'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import { filterMultiDictText, initDictOptions } from '@comp/dict/JDictSelectUtil';
  import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
  import { DragResizable } from '@/mixins/DragResizable'
  // import ErpRevokedDocFormApplyDetail from './ErpRevokedDocFormApplyDetail'
  import ErpReportReviewModel from '@/views/erp/omc/reportaudit/modules/reference/ErpReportReviewModel.vue'
  
  export default {
    name: 'SelectAuditFormListModel',
    components: {
      SelectTeamInput,
      SelectCompanyInput,
      ErpReportReviewModel,
    //   ErpRevokedDocFormApplyDetail,
      ErpProjectReportModal: () => import('@/views/erp/report/project/modules/ErpProjectReportModal')
    },
    mixins: [DragResizable],
    props: ['multi', 'urlList'],
    data() {
      return {
        title: '选择报告审核单',
        queryParam: {
          order: 'desc',
          column: 'createTime',
          billStatus: 'not_voided',
          bpmStatus:'3',
          billType:'create',
          permissionType:1
        },
        detailForm:null,
        dragResizeColumns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            },
            customCell: (record, index) => {
              let that = this
              return {
                on: {
                  click: () => {
                    that.selectedRowKeys = []
                    that.selectedRowKeys.push(record.id)
                    that.choseObj = []
                    that.choseObj.push(record)
                  }
                }
              }
            }
          },
          {
            title: '单据编号',
            align: 'center',
            dataIndex: 'billNo',
            width: 200,
            ellipsis: true,
            scopedSlots: { customRender: 'purchaseBill' },
            customCell: (record, index) => {
              let that = this
              return {
                on: {
                  click: () => {
                    that.selectedRowKeys = []
                    that.selectedRowKeys.push(record.id)
                    that.choseObj = []
                    that.choseObj.push(record)
                  }
                }
              }
            }
          },

          {
            title: '关联项目',
            align: 'center',
            dataIndex: 'projectId',
            width: 270,
            ellipsis: true,
            scopedSlots: { customRender: 'projectId' },
            customCell: (record, index) => {
              let that = this
              return {
                on: {
                  click: () => {
                    that.selectedRowKeys = []
                    that.selectedRowKeys.push(record.id)
                    that.choseObj = []
                    that.choseObj.push(record)
                  }
                }
              }
            },
            customRender: (text, r) => {
              if (!text) {
                return ''
              } else {
                return <a v-on:click={(e) => this.onDetail(text)}>{ filterMultiDictText(this.dictOptions['projectId'], text + '') }</a>;
              }
            }
          },

          {
            title: '费用所属团队',
            align: 'center',
            dataIndex: 'feeTeamId_dictText',
            width: 280,
            ellipsis: true,
            scopedSlots: { customRender: 'feeTeamId_dictText' },
            customCell: (record, index) => {
              let that = this
              return {
                on: {
                  click: () => {
                    that.selectedRowKeys = []
                    that.selectedRowKeys.push(record.id)
                    that.choseObj = []
                    that.choseObj.push(record)
                  }
                }
              }
            }
          },

          {
            title: '审核状态',
            align: 'center',
            dataIndex: 'bpmStatus',
            width: 100,
            ellipsis: true,
            scopedSlots: { customRender: 'bpmStatus' },
            customCell: (record, index) => {
              let that = this
              return {
                on: {
                  click: () => {
                    that.selectedRowKeys = []
                    that.selectedRowKeys.push(record.id)
                    that.choseObj = []
                    that.choseObj.push(record)
                  }
                }
              }
            },
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['bpmStatus'], text + '')
              }
            }
          },
          {
            title: '单据状态',
            align: 'center',
            dataIndex: 'billStatus_dictText',
            width: 100,
            ellipsis: true,
            scopedSlots: { customRender: 'billStatus_dictText' },
            customCell: (record, index) => {
              let that = this
              return {
                on: {
                  click: () => {
                    that.selectedRowKeys = []
                    that.selectedRowKeys.push(record.id)
                    that.choseObj = []
                    that.choseObj.push(record)
                  }
                }
              }
            },
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['bpmStatus'], text + '')
              }
            }
          }
        ],
        dataSource: [],
        choseObj: [],
        departTree: [],
        selectedKeys: [],
        iExpandedKeys: [],
        loading: false,
        treeData: [],
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        url: {
          queryByProjectId: '/api/erp/project/report/erpProjectReport/queryById',
          queryById: '/api/erp/omc/reportaudit/erpReportAudit/queryById',
          urlList: '/api/erp/omc/reportaudit/erpReportAudit/list'
        },
        selectedRowKeys: [],
        selectionRows: [],
        visible: false,
        dictOptions: {}
      }
    },
    created() {
      this.loadData()
      // 该方法触发屏幕自适应
      this.resetScreenSize()
      this.refresh()
      this.initDictConfig()
      this.initSource()
      this.dragResizeColumnswidth = this.dragResizeColumns.map(val => {
        return val.width
      })
    },
    computed: {
      // 计算属性的 getter
      getType: function () {
        return this.multi == true ? 'checkbox' : 'radio'
      }
    },
    methods: {
      initDictConfig() {
        // 关联项目
        initDictOptions('erp_omc_project,project_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'projectId', res.result)
          }
        })
        // 审核状态
        initDictOptions('bpm_status').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'bpmStatus', res.result)
          }
        })
      },
      goProjectDetail(record) {
        this.$nextTick(()=>{
          this.$refs.detailForm.edit(record)
        })
       
      },
       // 点击详情
      onDetail (id) {
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryByProjectId, { id: id }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectForm.getDetail(model);
              that.$refs.projectForm.title = '项目一览表';
            }
          })
        })
      },
      add(selectObj, ids) {
        this.visible = true
        this.loadData()
        this.edit(selectObj, ids)
      },
      edit(selectObj, ids) {
        if (!ids) {
          this.selectedRowKeys = []
        } else {
          this.selectedRowKeys = ids
        }
        if (!selectObj) {
          this.selectionRows = []
        } else {
          this.selectionRows = selectObj
          this.choseObj = selectObj
        }
        if (ids == null && selectObj == null) {
          this.selectionRows = []
          this.choseObj = []
          this.selectedRowKeys = []
        }
      },
      loadData(arg) {
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        var params = this.getQueryParams() // 查询条件
        params.order = 'desc',
        params.column = 'createTime',
        params.billStatus = 'not_voided',
        params.bpmStatus = '3',
        params.billType = 'create',
        params.permissionType = 1
        let tmpUrl = this.urlList
        this.loading = true
        getAction(tmpUrl, params).then((res) => {
          if (res.success) {
            if (res.result == null) {
              this.dataSource = []
              this.ipagination.total = 0
              return
            }
            this.dataSource = res.result.records
            this.ipagination.total = res.result.total
            if (this.orgCode === '') {
              // 第一次打开
            } else {
              for (var i = 0; i < this.dataSource.length; i++) {
                for (var j = 0; j < this.choseObj.length; j++) {
                  if (this.choseObj[j].id == this.dataSource[i].id) {
                    this.selectionRows.push(this.dataSource[i])
                    this.selectedRowKeys.push(this.dataSource[i].id)
                    break
                  }
                }
              }
            }
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1)
            }
          }
        }).finally(() => {
          this.loading = false
        })
      },
      loadTree() {
        var that = this
        that.treeData = []
        that.departTree = []
        queryDepartTreeList().then((res) => {
          if (res.success) {
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.treeData.push(temp)
              that.departTree.push(temp)
              that.setThisExpandedKeys(temp)
            }
            this.loading = false
          }
        })
      },
      getQueryParams() {
        let param = Object.assign({}, this.queryParam)
        param.field = this.getQueryField()
        param.pageNo = this.ipagination.current
        param.pageSize = this.ipagination.pageSize
        return filterObj(param)
      },
      getQueryField() {
        let str = 'id,'
        for (let a = 0; a < this.dragResizeColumns.length; a++) {
          str += ',' + this.dragResizeColumns[a].dataIndex
        }
        return str
      },
      onSelectAll(selected, selectedRows, changeRows) {
        if (selected === true) {
          for (var a = 0; a < changeRows.length; a++) {
            this.choseObj.push(changeRows[a])
          }
        } else {
          for (var b = 0; b < changeRows.length; b++) {
            this.choseObj.splice(this.choseObj.indexOf(changeRows[b]), 1)
          }
        }
      },
      onSelectOne(record, selected) {
        if (selected === true) {
          if (this.multi) {
            // 多选
            this.choseObj.push(record)
          } else {
            // 单选
            this.choseObj = []
            this.choseObj.push(record)
          }
        } else {
          if (this.multi) {
            // 多选
            var index = -1
            for (var i = 0; i < this.choseObj.length; i++) {
              if (this.choseObj[i].id == record.id) {
                index = i
                break
              }
            }
            if (index >= 0) {
              this.choseObj.splice(index, 1)
            }
          } else {
            // 单选
            this.choseObj = []
          }
        }
      },
      initSource() {
        this.selectedRowKeys = []
        this.selectionRows = []
        this.choseObj = []
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      searchReset() {
        let that = this
        Object.keys(that.queryParam).forEach(function (key) {
          if (key === 'status') {
            if (that.disableStatus === '1' && !that.projectStatus) {
              that.queryParam[key] = null
            }
          } else if (!!that.signUnit && key == 'signUnit') {
            that.queryParam[key] = that.queryParam[key]
          } else if (!!that.teamId && key == 'teamName2') {
            that.queryParam[key] = that.queryParam[key]
          } else if (!!that.costType && key == 'costType') {
            that.queryParam[key] = that.queryParam[key]
          } else {
            that.queryParam[key] = null
          }
        })
        this.queryParam.billStatus = '1'
        this.dataSource = []
        this.ipagination.total = 0
        that.loadData(1)
      },
      handleTableChange(pagination, filters, sorter) {
        // TODO 筛选
        // if (Object.keys(sorter).length > 0) {
        //   this.isorter.column = sorter.field
        //   this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        // }
        this.ipagination = pagination
        this.ipagination.current = pagination.current
        this.loadData()
      },
      handleCancel() {
        this.selectionRows = []
        this.selectedRowKeys = []
        this.visible = false
      },
      handleOk() {
        let data = {
          choseObj: this.choseObj,
          cutStatus: ''
        }
        this.$emit('choseObj', data)
        this.handleCancel()
      },
      searchByquery() {
        this.loadData(1)
      },
      handleToggleSearch() {
        this.toggleSearchStatus = !this.toggleSearchStatus
      },
      onSearch(value) {
        let that = this
        if (value) {
          searchByKeywords({ keyWord: value }).then((res) => {
            if (res.success) {
              that.departTree = []
              for (let i = 0; i < res.result.length; i++) {
                let temp = res.result[i]
                that.departTree.push(temp)
              }
            } else {
              that.$message.warning(res.message)
            }
          })
        } else {
          that.loadTree()
        }
      },
      setThisExpandedKeys(node) {
        if (node.children && node.children.length > 0) {
          this.iExpandedKeys.push(node.key)
          for (let a = 0; a < node.children.length; a++) {
            this.setThisExpandedKeys(node.children[a])
          }
        }
      },
      refresh() {
        this.loading = true
        this.loadTree()
      },
      onSelect(selectedKeys, e) {
        if (this.selectedKeys[0] !== selectedKeys[0]) {
          this.selectedKeys = [selectedKeys[0]]
        }
        let record = e.node.dataRef
        // this.selectionRows.push(record.id);
        this.onClearSelected()
        this.open(record)
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      open(record) {
        this.orgCode = record.orgCode
        this.loadData(1)
      },
      // 触发屏幕自适应
      resetScreenSize() {
        let screenWidth = document.body.clientWidth
        if (screenWidth < 500) {
          this.scrollTrigger = { x: 800 }
        } else {
          this.scrollTrigger = {}
        }
      },
      allObj() {
        this.selectedKeys = []
        this.onClearSelected()
        this.orgCode = null
        this.loadData(1)
      }
    }
  }
  </script>
  <style scoped>
  .ant-card-body .table-operator {
    margin-bottom: 18px;
  }
  
  .ant-table-tbody .ant-table-row td {
    padding-top: 15px;
    padding-bottom: 15px;
  }
  
  .anty-row-operator button {
    margin: 0 5px;
  }
  
  .ant-btn-danger {
    background-color: #ffffff;
  }
  
  .ant-modal-cust-warp {
    height: 100%;
  }
  
  .ant-modal-cust-warp .ant-modal-body {
    height: calc(100% - 110px) !important;
    overflow-y: auto;
  }
  
  .ant-modal-cust-warp .ant-modal-content {
    height: 90% !important;
    overflow-y: hidden;
  }
  
  .anty-img-wrap {
    height: 25px;
    position: relative;
  }
  
  .anty-img-wrap > img {
    max-height: 100%;
  }
  </style>
  